<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="关键词">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.keyword"
                placeholder="请输入名称或电话"></el-input>
            </el-form-item>
            <el-form-item label="工程经理">
              <el-select @change="onSearch(1)" v-model="formSearch.engineering_manager_id" filterable clearable
                placeholder="请选择工程经理" class="form-width">
                <el-option v-for="(item, idx) in gcList" :label="item.name" :value="item.id" :key="idx"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <!-- <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p> -->
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" @click="addFunc" v-if="$isPer(permission, ['foreman_add'])">新增工长</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选 <span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }} 数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editState"
            v-if="$isPer(permission, ['foreman_change'])">状态修改</el-button>
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['foreman_edit'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
            v-if="$isPer(permission, ['foreman_del'])">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" highlight-selection-row border
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="180px" prop="name" label="工长名称" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="phone" label="电话" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="sex" label="性别" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.sex == 1 ? '男' : '女' }}</template>
          </el-table-column>
          <el-table-column min-width="180px" prop="age" label="年龄" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.age }}岁</template>
          </el-table-column>
          <el-table-column min-width="180px" prop="job_type" label="工种" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="area" label="省市区" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="address" label="详细地址" show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="engineering_manager_name" label="工程经理"
            show-overflow-tooltip></el-table-column>
          <el-table-column min-width="180px" prop="is_use" label="状态" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.is_use == 1 ? '启用' : '停用' }}</template>
          </el-table-column>
          <el-table-column min-width="180px" prop="created_at" label="创建时间" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import foremanApi from '@/api/foremanApi'
import adminApi from '@/api/adminApi'

export default {
  name: "foremanList",
  data() {
    return {
      tableLoading: false,//列表loading
      tableData: [],//列表数据
      formSearch: { keyword: '' },//搜索form
      moreSearchShow: false,//
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],//多选数据
      gcList: [],
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch()
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })

    this.getList();
    this.getSearchList();
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    addFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/foremanAdd",
        query: {
          route_title: '新增工长'
        }
      })
    },
    editFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      let item = this.multipleSelection[0];
      this.$router.push({
        path: "/foremanAdd",
        query: {
          route_title: '编辑工长',
          sn: item.id
        }
      })
    },
    editState() {
      let item = this.multipleSelection[0];
      foremanApi.setForemanEnable({
        foreman_id: item.id,
        is_use: item.is_use == 1 ? 2 : 1
      }).then(res => {
        if (res.code == 200) {
          this.$message.success('修改成功')
          this.onSearch();
        } else {
          this.$message.error(res.message);
        }
      })
    },
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let id_arr = multipleSelection.map(item => item.id)
      let name_arr = multipleSelection.map(item => item.name)
      this.$confirm('是否删除【' + name_arr.join(', ') + '】?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        foremanApi.delForeman({ id_arr }).then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.onSearch();
          } else {
            this.$message.error(res.message);
          }
        })
      }).catch(() => { });

    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },



    // 获取列表数据
    getList() {
      this.tableLoading = true;
      let formSearch = this.formSearch
      foremanApi.getForemanList({
        page: this.page,
        num: this.num,
        keyword: formSearch.keyword,
        engineering_manager_id: formSearch.engineering_manager_id,
        show_deactivate: 1,
      }).then(res => {
        console.log(res, "获取工长")
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      }).catch(err => {
        this.tableLoading = false;
      })
    },
    getSearchList() {
      // 获取工程经理列表
      adminApi.getAdminList({
        page: 1,
        num: 999,
        position_id_arr: [7],
        identity: 2,
      }).then((res) => {
        console.log(res, "获取工程经理列表");
        if (res.code == 200) {
          this.gcList = res.data.list;
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
@import '@/styles/listPage.scss';
</style>